package util;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public final class JSONUtils {

    private static final Log LOG = LogFactory.getLog(JSONUtils.class);

    private JSONUtils(){
    	
    }
    
    /**
     * To convert model object to JSON string
     * 
     * @param obj
     * @return
     */
    public static String convertObjectToJSON(Object obj) {

        String jsonString = null;
        if (obj == null) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            jsonString = mapper.writeValueAsString(obj);
        } catch (JsonParseException e) {
            LOG.error(e.getMessage());
        } catch (JsonMappingException e) {
            LOG.error(e.getMessage());
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }

        return jsonString;
    }

    /**
     * To convert a json string to object (eg. model)
     * 
     * @param jsonString
     * @return
     */
    public static <T> T convertJSONToObject(Class<T> clazz, String jsonString) {

        T obj = null;
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();

        try {
            obj = mapper.readValue(jsonString, clazz);
        } catch (JsonParseException e) {
            LOG.error("convertJSONToObject::" + e.getMessage());
        } catch (JsonMappingException e) {
            LOG.error("convertJSONToObject::" + e.getMessage());
        } catch (IOException e) {
            LOG.error("convertJSONToObject::" + e.getMessage());
        }
        return obj;
    }
}
